#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2016 lizongzhe 
#
# Distributed under terms of the MIT license.
from conf.celery import app
from Task.models import Job, Task
from Task.exceptions import DependenceError
from Task import shortcuts
from datetime import datetime, timedelta

@app.task
def load_jobs():
    shortcuts.load_jobs()

@app.task
def process_jobs():
    ## celery WorkerLostError
    #Job.objects.filter(status=2, begin__lte=datetime.now() - timedelta(0, 30*60)).update(log='', status=0)

    pending_jobs = Job.objects.filter(status=Job.Status.pending)
    for job in pending_jobs:
        dependence_complete_jobs = []
        error_jobs = []
        try:
            if job.check_dependence_complete():
                dependence_complete_jobs.append(job.id)
                run_job.delay(job.id)
        except DependenceError:
            error_jobs.append(job.id)

        Job.objects.filter(pk__in=dependence_complete_jobs).update(status=Job.Status.waiting)
        Job.objects.filter(pk__in=error_jobs).update(status=Job.Status.error)

@app.task
def run_job(job_id):
    job = Job.objects.get(pk=job_id)
    job.start()
